package pers.ree.demo.misc;

import sun.misc.Unsafe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class UnsafeDemo {

    private static Unsafe getUnsafe() {
        try {
            return Unsafe.getUnsafe();
        } catch (SecurityException se) {
            try {
                Field field = Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                return (Unsafe) field.get(null);
            } catch (Exception e) {
                throw new AssertionError(e);
            }

            // 下面这段代码与Unsafe.class.getDeclaredField("theUnsafe")的作用等效
//            try {
//                Constructor<Unsafe> constructor = Unsafe.class.getDeclaredConstructor();
//                constructor.setAccessible(true);
//                return constructor.newInstance();
//            } catch (Exception e) {
//                throw new AssertionError(e);
//            }
        }
    }

    public static void main(String[] args) throws Exception {
        TestUnsafeEntity example = new TestUnsafeEntity();
        System.out.println(example.getValue());

        Unsafe unsafe = getUnsafe();
        Field field = TestUnsafeEntity.class.getDeclaredField("value");
        long fieldOffset = unsafe.objectFieldOffset(field);
        int value = unsafe.getInt(example, fieldOffset);
        // 直接设置字段值，绕过setter
        unsafe.putInt(example, fieldOffset, 100);

        System.out.println(example.getValue());
    }
}
